# 导入库
from flask_sqlalchemy import SQLAlchemy
from flask import Flask

app = Flask(__name__)

# 配置信息
class DbConfig(object):
    # 设置连接数据库的url
    SQLALCHEMY_DATABASE_URI = "mysql+pymysql://root:12345@localhost:3306/flask_test"
    # 设置每次请求结束后会自动提交数据库中的改动
    SQLALCHEMY_COMMIT_ON_TEARDOWN = True
    # 可修改
    SQLALCHEMY_TRACK_MODIFICATIONS = True
    # 查询时会显示原始SQL语句
    SQLALCHEMY_ECHO = True
# 初始化配置
app.config.from_object(DbConfig)
# 获取SQLAlchemy对象
db = SQLAlchemy(app)

class PhoneType(db.Model):
    # 定义表名
    __tablename__ = "tbl_phonetype"
    # 类型ID、类型名
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    name = db.Column(db.String(64),unique=True)
    # 关联
    phone = db.relationship("Phone",backref="phonetype")
    def __str__(self):
        return "PhoneType:%s"%self.name

class Phone(db.Model):
    # 定义表名
    __tablename__ = "tbl_phone"
    # 手机ID、品牌名、手机型号、价格
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    brand = db.Column(db.String(64),unique=True)
    name = db.Column(db.String(64),unique=True,index=True)
    price = db.Column(db.Float)
    # 外键约束
    type_id = db.Column(db.Integer,db.ForeignKey("tbl_phonetype.id"))
    # 型号
    def __str__(self):
        return "手机型号:%s"%self.name

if __name__ == '__main__':
    # # 删除表内所有数据
    # db.drop_all()
    # # 创建所有表
    # db.create_all()
    #
    # 创建类型对象1
    type_obj1 = PhoneType(name="商务型")
    # db.session.add(type_obj1)
    # 创建类型对象2
    type_obj2 = PhoneType(name="游戏类")
    # db.session.add(type_obj2)
    # # 提交
    # db.session.commit()

    # 多个手机
    phone1 = Phone(brand="HUAWEI",name="Mate 40",price=8999,type_id=type_obj1.id)
    phone2 = Phone(brand="Apple",name="iPhone 12",price=6999,type_id=type_obj1.id)
    phone3 = Phone(brand="黑鲨",name="腾讯黑鲨手机3",price=3999,type_id=type_obj2.id)
    phone4 = Phone(brand="MI",name="Mi 10",price=8999,type_id=type_obj2.id)
    # 添加多个
    db.session.add_all([phone1,phone2,phone3,phone4])
    # 提交
    db.session.commit()
    app.run(debug=True)

